﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kugar.Core.BaseStruct;
using Kugar.Core.ExtMethod;

using Kugar.MVC.MobileUI.WeUI.Helpers;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

#if !NETCOREAPP
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
#endif

#if NETCOREAPP

using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Kugar.Core.Web;
#endif


namespace Kugar.MVC.MobileUI.WeUI.PageControls.PageCommons
{
    /// <summary>
    /// 取数窗口
    /// </summary>
    public class PageCommon_DataPicker<TData>:ControlBase
    {
        private string _title = "";
        private PopupShowSide _side = PopupShowSide.RightToLeft;
        private bool _isMultiSelect = false;
        private IEnumerable<TData> _data;
        private int _pageCount = 1;
        private Func<TData, JObject> _rowValueFunc = null;
        private Func<TData, bool> _checkedFunc = null;
        private string _callOnLoadMore = "";
        private Func<TData, PageCommon_DataPicker<TData>, string> _renderRow = null;
        private Lazy<List<ButtonItemBase>> _buttonList=new Lazy<List<ButtonItemBase>>();
        private int _currentIndex = 0;
        private JObject _currentRowValue = null;
        private string _pageIndexKey = "pageindex";
        private ItenTemplate<TData> _template = null;

        public PageCommon_DataPicker(ViewContext viewContext) : base(viewContext)
        {
            this.Css("weui-popup__container popup-bottom weui-popup_datapicker");
        }

        /// <summary>
        /// 允许滚动加载,并需设置触发脚本
        /// </summary>
        /// <param name="callOnNeed"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> EnableLoadingMore(string callOnNeed)
        {
            _callOnLoadMore = callOnNeed;

            return this;
        }

        /// <summary>
        /// 标题
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> Title(string title)
        {
            _title = title;

            return this;
        }

        /// <summary>
        /// 显示的方向
        /// </summary>
        /// <param name="side"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> ShowSide(PopupShowSide side = PopupShowSide.RightToLeft)
        {
            _side = side;

            return this;
        }

        /// <summary>
        /// 是否允许多选
        /// </summary>
        /// <param name="isMultiSelect"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> MultiSelect(bool isMultiSelect = true)
        {
            _isMultiSelect = isMultiSelect;

            return this;
        }

        /// <summary>
        /// 数据列表
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> Data(IEnumerable<TData> data)
        {
            _data = data;

            return this;
        }

        public PageCommon_DataPicker<TData> Data(VM_PagedList<TData> data)
        {
            _data = data.Data;
            _pageCount = data.PageCount;
            return this;
        }

        /// <summary>
        /// 行数据
        /// </summary>
        /// <param name="rowValueFunc"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> RowValue(Func<TData, JObject> rowValueFunc)
        {
            _rowValueFunc = rowValueFunc;
            return this;
        }

        /// <summary>
        /// 默认选中的项目
        /// </summary>
        /// <param name="checkedFunc">返回是否选中该数据项</param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> Checked(Func<TData, bool> checkedFunc)
        {
            _checkedFunc = checkedFunc;

            return this;
        }

        /// <summary>
        /// 自定义列表项模板
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> CustomTemplate(Func<TData, PageCommon_DataPicker<TData>, HelperResult> func)
        {
            _renderRow = (data,picker) => func(data, picker).ToHtmlString();

            return this;
        }

        /// <summary>
        /// 带图标的列表项模板
        /// </summary>
        /// <param name="templateConfigFunc"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> MediaBoxTemplate(Action<TData, PageCommon_DataPicker<TData>, MediaBoxItemConfig<TData>> templateConfigFunc)
        {
            var config = new MediaBoxItemConfig<TData>(this);

            _template = config;

            return this;
        }

        /// <summary>
        /// 文本列表项模板
        /// </summary>
        /// <param name="textTemplateConfigFunc"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> TextTemplate(Func<TData, PageCommon_DataPicker<TData>, string> textTemplateConfigFunc)
        {
            _template=new TextItemConfig<TData>(this,textTemplateConfigFunc);

            //_renderRow = (data, picker) => textTemplateConfigFunc(data, picker);

            return this;
        }

        /// <summary>
        /// 添加一个按钮
        /// </summary>
        /// <param name="configFunc"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> AddButton(Action<ButtonItemBase> configFunc)
        {
            var config = new ButtonItemBase();

            configFunc(config);

            _buttonList.Value.Add(config);

            return this;
        }

        /// <summary>
        /// 当前行序号
        /// </summary>
        public int CurrentIndex => _currentIndex;

        public JObject CurrentRowValue => _currentRowValue;
        

        public override MvcHtmlString Render()
        {
            var sideCss = "";

            if (_side != PopupShowSide.BottomToTop)
            {
                switch (_side)
                {
                    case PopupShowSide.TopToBottom:
                        sideCss = "fromTop";
                        break;
                    case PopupShowSide.LeftToRight:
                        sideCss = "fromLeft";
                        break;
                    case PopupShowSide.RightToLeft:
                        sideCss = "fromRight";
                        break;
                }

                this.Css(sideCss);
            }

            //if (_pageCount>1)
            //{
            //    this.Data("loadmore", "True");
            //    //this.Data("loadmorecallback", _callOnLoadMore);
            //}

#if NETCOREAPP
            _attrs.Data("url", ViewContext.HttpContext.Request.GetDisplayUrl());
#endif
#if !NETCOREAPP
      _attrs.Data("url", ViewContext.RequestContext.HttpContext.Request.RawUrl);
#endif



            _attrs.Data("pageindexkey", _pageIndexKey);

            ViewContext.Writer.WriteLine($"<div {_attrs}>");
            ViewContext.Writer.WriteLine("<div class=\"weui-popup__overlay\"></div>");
            ViewContext.Writer.WriteLine("<div class=\"weui-popup__modal\">");

            if (!string.IsNullOrWhiteSpace(_title))
            {
                ViewContext.Writer.WriteLine($"<div class=\"toolbar\"><div class=\"toolbar-inner\"><a href=\"javascript:;\" class=\"picker-button close-popup\">关闭</a><h1 class=\"title\">{_title}</h1></div></div>");
            }

            ViewContext.Writer.WriteLine($"<div class=\"modal-content\" {(_pageCount>1? "data-loadmore=\"True\"" : "")}>");

            _currentIndex = 0;
            _currentRowValue = null;

            ViewContext.Writer.WriteLine(_template.BeginContainer());

            foreach (var data in _data)
            {
                _currentRowValue = _rowValueFunc?.Invoke(data);
                var isChecked = _checkedFunc?.Invoke(data);
                _currentIndex++;

                if (_currentIndex == 1)
                {

                }

                ViewContext.Writer.WriteLine(_template.Build(data));
            }

            ViewContext.Writer.WriteLine(_template.EndContainer());

            ViewContext.Writer.WriteLine("</div> <!-- end  modal-content -->");

            ViewContext.Writer.WriteLine("<div class=\"weui-flex weui_datapicker_button\">");

            ViewContext.Writer.WriteLine("<div class=\"weui-flex__item\"><button type=\"button\" class=\"weui-btn weui-btn_primary btn-select\">选择</button></div>");

            if (_buttonList.IsValueCreated && _buttonList.Value.HasData())
            {
                foreach (var btn in _buttonList.Value)
                {
                    ViewContext.Writer.WriteLine("<div class=\"weui-flex__item\">");

                    ViewContext.Writer.WriteLine(Utility.ButtonConfigToHtml(btn, "button"));

                    ViewContext.Writer.WriteLine("</div>");
                }
            }

            ViewContext.Writer.WriteLine("</div> <!-- ebnd weui_datapicker_button -->");

            ViewContext.Writer.WriteLine("</div> <!-- end popup__modal -->");

            ViewContext.Writer.WriteLine("</div> <!-- end popup__container -->");

            return MvcHtmlString.Empty;
        }

        public abstract class ItenTemplate<TRowData>
        {
            public virtual string BeginContainer() { return String.Empty;}

            public virtual string EndContainer() { return String.Empty;}

            public abstract string Build(TRowData data);
        }

        public class MediaBoxItemConfig<TData>: ItenTemplate<TData>
        {
            private Func<TData, string> _iconGetter = null;
            private Func<TData, string> _titleGetter = null;
            private Func<TData, string> _descGetter = null;
            private Func<TData, string> _rightTitleGetter = null;
            private Func<TData, string> _badgeGetter = null;
            private Func<TData, string> _linkGetter = null;
            private string _iconSize = "48px";

            private PageCommon_DataPicker<TData> _picker = null;

            public MediaBoxItemConfig(PageCommon_DataPicker<TData> picker)
            {
                _picker = picker;
            }

            public MediaBoxItemConfig<TData> Title(Func<TData, string> titleGetter)
            {
                _titleGetter = titleGetter;

                return this;
            }

            public MediaBoxItemConfig<TData> Title(Func<TData, HelperResult> titleGetter)
            {
                _titleGetter = (data) => titleGetter(data).ToHtmlString();

                return this;
            }

            public MediaBoxItemConfig<TData> Icon(Func<TData, string> iconGetter)
            {
                _iconGetter = iconGetter;

                return this;
            }

            public MediaBoxItemConfig<TData> Desc(Func<TData, HelperResult> descGetter)
            {
                _descGetter = (data) => descGetter(data).ToHtmlString();

                return this;
            }

            public MediaBoxItemConfig<TData> Desc(Func<TData, string> descGetter)
            {
                _descGetter = descGetter;

                return this;
            }

            public MediaBoxItemConfig<TData> RightTitle(Func<TData, string> rightTitleGetter)
            {
                _rightTitleGetter = rightTitleGetter;

                return this;
            }

            public MediaBoxItemConfig<TData> Badge(Func<TData, string> badgeGetter)
            {
                _badgeGetter = badgeGetter;

                return this;
            }

            public MediaBoxItemConfig<TData> Link(Func<TData, string> linkGetter)
            {
                _linkGetter = linkGetter;

                return this;
            }

            public MediaBoxItemConfig<TData> IconSize(string iconSize = "48px")
            {
                _iconSize = iconSize;

                return this;
            }

            public override string Build(TData data)
            {
                var sb = new StringBuilder(256);

                sb.AppendLine(
                    $"<a href=\"{_linkGetter?.Invoke(data) ?? "javascript:void(0);"}\" class=\"weui-media-box weui-media-box_appmsg\">");

                var iconUrl = _iconGetter?.Invoke(data);

                if (!string.IsNullOrWhiteSpace(iconUrl))
                {
                    sb.AppendLine("<div class=\"weui-media-box__hd\">");

                    if (!string.IsNullOrWhiteSpace(iconUrl))
                    {
                        sb.AppendLine($"<img class=\"weui-media-box__thumb\" src=\"{iconUrl}\" width=\"{_iconSize}\" height=\"{_iconSize}\" alt=\"\" />");
                    }

                    var badge = _badgeGetter?.Invoke(data) ?? "";

                    if (!string.IsNullOrWhiteSpace(badge))
                    {
                        sb.AppendLine(
                            $"<span class=\"weui-badge\" style=\"position: absolute;top: -.4em;right: -.4em;\">{badge}</span>");
                    }

                    sb.AppendLine("</div> <!-- end box__hd -->");
                }

                sb.AppendLine("<div class=\"weui-media-box__bd\">");
                sb.AppendLine($"<h4 class=\"weui-media-box__title\">{_titleGetter?.Invoke(data) ?? ""}");
                sb.AppendLine($"<span class=\"weui-media-box__title-after\">{_rightTitleGetter?.Invoke(data) ?? ""}</span>");
                sb.AppendLine("</h4>");


                sb.AppendLine($"<p class=\"weui-media-box__desc\">{_descGetter?.Invoke(data) ?? ""}</p>");
                sb.AppendLine("</div> <!-- end  box__bd-->");
                sb.AppendLine("</a>");

                var value = sb.ToString();

                sb.Clear();

                return value;
            }
        }

        public class TextItemConfig<TData> : ItenTemplate<TData>
        {
            private PageCommon_DataPicker<TData> _picker = null;
            private Func<TData, PageCommon_DataPicker<TData>, string> _textTemplateConfigFunc;

            public TextItemConfig(PageCommon_DataPicker<TData> picker,
                Func<TData, PageCommon_DataPicker<TData>, string> textTemplateConfigFunc)
            {
                _picker = picker;
                _textTemplateConfigFunc = textTemplateConfigFunc;
            }

            public override string BeginContainer()
            {
                return "<div class=\"weui-cells weui-cells_checkbox weui-cell-datapicker_list\">";
            }

            public override string EndContainer()
            {
                return "</div>";
            }

            public override string Build(TData data)
            {
                /*
                 <label class="weui-cell weui-check__label" for="s11">
                    <div class="weui-cell__hd">
                      <input type="checkbox" class="weui-check" name="checkbox1" id="s11" checked="checked">
                      <i class="weui-icon-checked"></i>
                    </div>
                    <div class="weui-cell__bd">
                      <p>standard is dealt for u.</p>
                    </div>
                  </label>
                 */

                var id ="chk_" + _picker.WeUI.NextControlID();

                var sb =new StringBuilder();

                sb.AppendLine($"<label class=\"weui-cell weui-check__label weui-datapicker_selectitem\" for=\"{id}\">");


                sb.AppendLine("<div class=\"weui-cell__hd\">");
                sb.AppendLine(
                    $"<input type=\"{_picker._isMultiSelect.If("checkbox","radio")}\" class=\"weui-check\" name=\"checkbox1\" id=\"{id}\" value='{_picker.CurrentRowValue.ToStringEx(Formatting.None)}'>");
                sb.AppendLine("<i class=\"weui-icon-checked\"></i>");
                sb.AppendLine("</div>");

                sb.AppendLine($"<div class=\"weui-cell__bd\">{_textTemplateConfigFunc(data,_picker)}</div>");
                
                sb.AppendLine("</label>");

                return sb.ToStringEx();
            }
        }
    }
}